//vm: vm实例对象
//exp: 表达式
//cb: 回调函数
function Watcher(vm, exp, cb) {
    //this:Watcher实例
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;

    //depIds : 存和当前watcher实例相关的dep的id!!!!
    this.depIds = {};
    //value: 表达式所对应的值!!!
    this.value = this.get();
}

Watcher.prototype = {

    get: function() {
        Dep.target = this;//this:Watcher实例
        var value = this.getVMVal();
        Dep.target = null;
        return value;
    },

    getVMVal: function() {
        var exp = this.exp.split('.');
        var val = this.vm._data;
        exp.forEach(function(k) {
            val = val[k];
        });
        return val;
    },

    addDep: function(dep) {
        if (!this.depIds.hasOwnProperty(dep.id)) {
            //dep和watcher的多对多关系!!!!
            dep.addSub(this);
            this.depIds[dep.id] = dep;
        }
    },

    update: function() {
        this.run();
    },

    run: function() {
        var value = this.get();
        var oldVal = this.value;
        if (value !== oldVal) {
            this.value = value;
            this.cb.call(this.vm, value, oldVal);
        }
    },
};